﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Text;
using System.Globalization;
using TanHungViet.Web.Models;
using TanHungViet.Helper;
using System.Net;
using System.Net.Mail;
using System.IO;
using log4net;

namespace TanHungViet.Web.Controllers
{
    public class TanHungVietController : Controller
    {
        private static ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


        // ++Index
        public ActionResult Index()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            PaginatedList<Product> model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ProductRepository productRepository = new ProductRepository(entity);
                var models = productRepository.GetListProductForHomePage().OrderByDescending(b => b.ProductID);
                model = new PaginatedList<Product>(models, 0, Constant.PageSize2);
            }

            ViewData["ContentCode"] = "home-page";
            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangChu", new CultureInfo(cultureInfo));

            return View("SanPham", model);
        }
        // --Index

        #region UserControl
        ////////////////////////////////////////////////////////////////////////////////////////////////  
        // ++ UserControl //////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////
        // ++ Menu Ngang
        public ActionResult MenuNgang()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            List<MenuItem> model = new List<MenuItem>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                MenuRepository menuRepository = new MenuRepository(entity);
                model = menuRepository.GetDynamicMenu(cultureInfo, false);
            }

            return View(model);
        }
        // -- Menu Ngang

        // ++ Menu Doc
        public ActionResult MenuDoc()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            List<MenuItem> model = new List<MenuItem>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                MenuRepository menuRepository = new MenuRepository(entity);
                model = menuRepository.GetDynamicMenu(cultureInfo, true);
            }

            return View(model);
        }
        // -- Menu Doc

        // ++ Noi Dung Ben Trai
        public ActionResult NoiDungBenTrai()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode(Constant.CodeNoiDungBenTrai, cultureInfo);
            }

            return View(model);
        }
        // -- Noi Dung Ben Trai

        // ++ Thoi Gian Lam Viec
        public ActionResult ThoiGianLamViec()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode(Constant.CodeNoiDungThoiGianLamViec, cultureInfo);
            }

            return View("NoiDungBenTrai", model);
        }
        // -- Thoi Gian Lam Viec

        // ++ Thoi Gian Lam Viec
        public ActionResult QuangCaoBenPhai()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode(Constant.CodeNoiDungQuangCaoBenPhai, cultureInfo);
            }

            return View("NoiDungBenTrai", model);
        }
        // -- Thoi Gian Lam Viec
        ////////////////////////////////////////////////////////////////////////////////////////////////  
        // -- UserControl //////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////
        #endregion


        #region Cac noi dung 1 bai viet
        ////////////////////////////////////////////////////////////////////////////////////////////////  
        // ++ Cac noi dung 1 bai viet //////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult GioiThieu(string code)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode(code, cultureInfo);
            }

            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangGioiThieu", new CultureInfo(cultureInfo));
            return View("ChiTietNoiDung", model);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult TuyenDung()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode("tuyen-dung", cultureInfo);
            }

            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangTuyenDung", new CultureInfo(cultureInfo));
            return View("ChiTietNoiDung", model);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult LienHe()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode("lien-he", cultureInfo);
            }

            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangLienHe", new CultureInfo(cultureInfo));
            return View("ChiTietNoiDung", model);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult DaiLy()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode("dai-ly", cultureInfo);
            }

            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangDaiLy", new CultureInfo(cultureInfo));
            return View("ChiTietNoiDung", model);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult ThanhToan()
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode("thanh-toan", cultureInfo);
            }

            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangThanhToan", new CultureInfo(cultureInfo));
            return View("ChiTietNoiDung", model);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////  
        // -- Cac noi dung 1 bai viet //////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////
        #endregion

        #region Sitemap
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult Sitemap()
        {
            List<MenuItem> model = new List<MenuItem>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                MenuRepository menuRepository = new MenuRepository(entity);
                string cultureInfo = "";
                model = menuRepository.GetDynamicMenu(cultureInfo, false);
                model.AddRange(menuRepository.GetDynamicMenu(cultureInfo, true));
            }

            return View(model);
        }
        #endregion

        #region Tin Tuc
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult TinTuc(string code, int? page)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            PaginatedList<Content> model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                var contents = contentRepository.GetListContentByParentCode(code, cultureInfo).OrderByDescending(b => b.ContentID);
                model = new PaginatedList<Content>(contents, page - 1 ?? 0, Constant.PageSize2);
                ViewData["PageTitle"] = contentRepository.GetContentByCode(code, cultureInfo).ContentTitle;
            }

            ViewData["ParentCode"] = code;
            return View(model);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////
        
        public ActionResult TinTucMoi()
        {
            
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();
            List<Content> model= new List<Content>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                var temp = contentRepository.GetListContentByContentParent(cultureInfo);
                int countNews = 4;
                if (temp.Count < countNews)
                    countNews = temp.Count;
                for (int i = 0; i < countNews; i++)
                {
                    Content n = temp[i];
                    model.Add(n);
                }
            }

            return View(model);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult ChiTietTinTuc(string code)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Content model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetContentByCode(code, cultureInfo);
                var parent = contentRepository.GetParentByContentCode(code, cultureInfo);
                ViewData["ParentTitle"] = parent.ContentTitle;
                ViewData["ParentCode"] = parent.ContentCode;
            }

            ViewData["PageTitle"] = ResourceUtil.Instance.GetString("TrangChiTietTinTuc", new CultureInfo(cultureInfo));
            return View(model);
        }
        #endregion


        #region TaiLieu
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult TaiLieu(string code, int? page)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            PaginatedList<Models.FileInfo> model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                FileInfoRepository fileInfoRepository = new FileInfoRepository(entity);
                var models = fileInfoRepository.GetListFileByContentCode(code).OrderByDescending(b => b.FileID);
                model = new PaginatedList<Models.FileInfo>(models, page - 1 ?? 0, Constant.PageSize2);
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["PageTitle"] = contentRepository.GetContentByCode(code, cultureInfo).ContentTitle;
            }

            ViewData["ParentCode"] = code;
            ViewData["ViewName"] = ResourceUtil.Instance.GetString("TaiLieu", new CultureInfo(cultureInfo));
            return View("DanhSachTapTin", model);
        }
        #endregion

        #region Download
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult Download(string code, int? page)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            PaginatedList<Models.FileInfo> model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                FileInfoRepository fileInfoRepository = new FileInfoRepository(entity);
                var models = fileInfoRepository.GetListFileByContentCode(code).OrderByDescending(b => b.FileID);
                model = new PaginatedList<Models.FileInfo>(models, page - 1 ?? 0, Constant.PageSize2);
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["PageTitle"] = contentRepository.GetContentByCode(code, cultureInfo).ContentTitle;
            }

            ViewData["ParentCode"] = code;
            ViewData["ViewName"] = "Download";
            return View("DanhSachTapTin", model);
        }
        #endregion


        #region Download Tap Tin
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public ActionResult DownloadTapTin(string code)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                FileInfoRepository fileInfoRepository = new FileInfoRepository(entity);
                ViewData["FileTitle"] = fileInfoRepository.GetFullFileInfoByCode(code).FileTitle;
            }

            ViewData["FileCode"] = code;
            return View();
        }

        [HttpPost()]
        public ActionResult DownloadTapTin(FormCollection collection)
        {
            string hoTen = collection["txtHoten"];
            string tenCty = collection["txtTenCty"];
            string dcCty = collection["txtDchiCty"];
            string dienThoai = collection["txtDienThoai"];
            string email = collection["txtEmail"];
            string code = collection["hidFileCode"];
            string fileTitle = string.Empty;
            string fileName = string.Empty;
            string fileExten = string.Empty;

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                FileInfoRepository fileInfoRepository = new FileInfoRepository(entity);
                var fileInfo = fileInfoRepository.DownloadFile(code);
                fileTitle = fileInfo.FileTitle;
                fileExten = fileInfo.FileExtension;
                fileName = fileInfo.FileCode + fileExten;
            }
            string urlFile = string.Empty;

            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(email);
                mail.To.Add("nguyenthetrinh84@gmail.com");
                mail.Subject = "Thông tin download từ website tanhungviet.vn";
                mail.Body = "Đây là email tự động từ trang web tanhungviet.vn khi có khách hàng download tập tin từ website"
                    + "\n" + "\n" + "\n"
                    + "\t" + "Tên tập tin : " + fileTitle + "\n" + "\n"
                    + "\t" + "Thông tin khách hàng download tập tin" + "\n"
                    + "\t" + "\t" + "Họ tên : " + hoTen + "\n"
                    + "\t" + "\t" + "Tên công ty : " + tenCty + "\n"
                    + "\t" + "\t" + "Địa chỉ công ty : " + dcCty + "\n"
                    + "\t" + "\t" + "Số điện thoại : " + dienThoai + "\n"
                    + "\t" + "\t" + "Email : " + email + "\n" + "\n";
                mail.IsBodyHtml = false;
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                string userName, password;
                using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
                {
                    ParameterRepository paramRepository = new ParameterRepository(entity);
                    userName = paramRepository.GetParamValue(Constant.ParamEmailAcc);
                    password = paramRepository.GetParamValue(Constant.ParamEmailPwd);
                }

                client.Credentials = new NetworkCredential(userName, password);
                client.EnableSsl = true;
                client.Send(mail);
            }
            catch (Exception e)
            {
                _logger.Error(e);
            }
            finally
            {
                urlFile = @"http://" + Request.Url.Host + ":" + Request.Url.Port.ToString() + @"/Content/files/" + fileName;  
            }
            //string downloadFileName = Path.Combine(
            //       Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
            //       Constant.FolderFile),
            //       Path.GetFileName(fileName));

            //WebClient webClient = new WebClient();
            //HttpContext.Response.Clear();
            //HttpContext.Response.ClearContent();
            //HttpContext.Response.ClearHeaders();
            //HttpContext.Response.Buffer = true;
            //HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            //byte[] data = webClient.DownloadData(downloadFileName);
            //HttpContext.Response.BinaryWrite(data);
            //HttpContext.Response.End();

            //return File(data, "application/*", fileName);

            return Redirect(urlFile);
            //return RedirectToAction("Index");
        }
        #endregion


        #region San Pham
        public ActionResult SanPham(string code, int? page)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            PaginatedList<Product> model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["PageTitle"] = contentRepository.GetContentByCode(code, cultureInfo).ContentTitle;

                ProductRepository productRepository = new ProductRepository(entity);
                var models = productRepository.GetListProductByContentCode(code).OrderByDescending(b => b.ProductID);
                model = new PaginatedList<Product>(models, page - 1 ?? 0, Constant.PageSize2);
            }

            ViewData["ParentCode"] = code;
            ViewData["ViewName"] = ResourceUtil.Instance.GetString("TaiLieu", new CultureInfo(cultureInfo));
            return View(model);
        }

        public ActionResult ChiTietSanPham(string code)
        {
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            Product model;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ProductRepository productRepository = new ProductRepository(entity);
                model = productRepository.GetFullProductByCode(code);
                ViewData["PageTitle"] = model.ProductName;
            }

            ViewData["ViewName"] = ResourceUtil.Instance.GetString("TaiLieu", new CultureInfo(cultureInfo));
            return View(model);
        }

        public ActionResult DatMua(int code)
        {
            Dictionary<int, int> cart = Session["Cart"] as Dictionary<int, int>;
            if (cart.ContainsKey(code))
                cart[code] += 1;
            else
            {
                int countCart = (int)Session["CountCart"];
                Session["CountCart"] = countCart + 1;
                cart.Add(code, 1);
            }

            return RedirectToAction("ChiTietGioHang");
        }

        public ActionResult ChiTietGioHang()
        {
            Dictionary<int, int> cart = Session["Cart"] as Dictionary<int, int>;
            List<int> listProductID = cart.Keys.ToList<int>();
            List<Product> model = new List<Product>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ProductRepository productRepository = new ProductRepository(entity);
                model = productRepository.GetListProductByListID(listProductID);
            }

            decimal total = 0;
            foreach (var n in model)
            {
                int id = n.ProductID;
                n.Count = cart[id];
                n.Cost = n.Count * (n.ProductPrice ?? 0);
                total += n.Cost;
            }

            ViewData["Total"] = total;
            return View(model);
        }
        #endregion


        #region Dat cau hoi
        [HttpPost()]
        public JsonResult DatCauHoi(string emailInfo)
        {
            try
            {
                string[] array = emailInfo.Split('~');

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(array[1]);
                mail.To.Add("nguyenthetrinh84@gmail.com");
                mail.Subject = "Câu hỏi cần tư vấn từ website tanhungviet.com.vn";
                mail.Body = "Đây là email tự động từ trang web tanhungviet.com.vn khi có khách hàng gửi câu hỏi tư vấn" + "\n" + "\n"
                    + "Thông tin khách hàng cần tư vấn : " + array[0] + "\n"
                    + "\t" + "Họ tên : " + array[0] + "\n"
                    + "\t" + "Địa chỉ email : " + array[1] + "\n"
                    + "\t" + "Số điện thoại : " + array[2] + "\n"
                    + "\t" + "Tiêu Đề  : " + array[3] + "\n" + "\n"
                    + "Nội dung : " + "\n" + array[4];
                mail.IsBodyHtml = false;

                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                string userName, password;
                using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
                {
                    ParameterRepository paramRepository = new ParameterRepository(entity);
                    userName = paramRepository.GetParamValue(Constant.ParamEmailAcc);
                    password = paramRepository.GetParamValue(Constant.ParamEmailPwd);
                }
                client.Credentials = new NetworkCredential(userName, password);
                client.EnableSsl = true;
                client.Send(mail);

                return this.Json(new { mess = "Gửi câu hỏi tư vấn thành công" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.Json(new { mess = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        //RSS Feed
        public ActionResult RSS(string code)
        {
            string fullUrl = Request.Url.OriginalString;
            ViewData["DNS"] = fullUrl.Substring(0, fullUrl.IndexOf("/RSS"));

            string type = code.Substring(0, 1);
            string parentCode = code.Substring(1);
            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                IEnumerable<TanHungViet.Web.Models.Content> contents = contentRepository.GetListContentByParentCode(parentCode, cultureInfo).OrderBy(b => b.ContentID);
                ListContent listContent = new ListContent();
                foreach (var item in contents)
                {
                    listContent.Items.Add(item);
                }
                if (type == "1")
                    return View("ChuyenMucTinTuc", listContent);
                else
                {
                    if (type == "2")
                        return View("ChuyenMucTuVan", listContent);
                    else
                        return View("ChuyenMucHoiDap", listContent);
                }
            }
        }
        #endregion


        #region Tim Kiem
        public ActionResult TimKiem(string code, int? page)
        {
            string keywordVN = Helper.Util.ConvertToUnsignString(code.Trim().ToLower());
            List<SearchResultItem> searchResult = new List<SearchResultItem>();
            List<Content> listContent = new List<Content>();
            List<Product> listProduct = new List<Product>();
            List<Models.FileInfo> listFile = new List<TanHungViet.Web.Models.FileInfo>();

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listContent = contentRepository.GetListContentDetailByType("none").OrderByDescending(b => b.ContentID).ToList<Content>();

                ProductRepository productRepository = new ProductRepository(entity);
                listProduct = productRepository.GetFullListProduct().OrderByDescending(b => b.ProductID).ToList<Product>();

                FileInfoRepository fileInfoRepository = new FileInfoRepository(entity);
                listFile = fileInfoRepository.GetFullListFile().OrderByDescending(b => b.FileID).ToList<Models.FileInfo>();

            }

            // ++ search san pham
            for (int i = 0; i < listProduct.Count; i++)
            {
                Product product = listProduct[i];
                string nameCode = Helper.Util.ConvertToUnsignString(product.ProductName.ToLower());
                string name2 = string.IsNullOrEmpty(product.ProductName2) ? string.Empty : product.ProductName2;
                if (nameCode.Contains(keywordVN)
                    || name2.Contains(code))
                {
                    SearchResultItem searchItem = new SearchResultItem();
                    searchItem.Title = product.ProductName;
                    searchItem.PublishDate = product.UpdateDate ?? DateTime.Now;
                    searchItem.Link = Url.Action("ChiTietSanPham", new { code = product.ProductCode });

                    searchResult.Add(searchItem);
                }
            }
            // -- search san pham

            // ++ search content
            for (int i = 0; i < listContent.Count; i++)
            {
                Content content = listContent[i];
                if (content.ContentParent == Constant.IDTinTuc
                    || content.ContentParent == Constant.IDSanPham)
                {
                    listContent.RemoveAt(i);
                    i--;
                }
            }

            List<int> parentIDs = new List<int>();
            parentIDs.Add(Constant.IDTinTuc);
            List<int> listTemp = new List<int>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listTemp = contentRepository.GetChildIDByParent(parentIDs);
            }
            foreach (var content in listContent)
            {
                if (!string.IsNullOrEmpty(content.ContentTitle))
                {
                    string itemTitle = TanHungViet.Helper.Util.ConvertToUnsignString(content.ContentTitle.ToLower());
                    string itemTitle2 = string.IsNullOrEmpty(content.ContentTitle2) ? string.Empty : content.ContentTitle2;
                    if (itemTitle.Contains(keywordVN)
                        || itemTitle2.Contains(code))
                    {
                        string action = string.Empty;
                        if (content.ContentParent == Constant.IDGioiThieu)
                            action = "GioiThieu";
                        else if(content.ContentParent == Constant.IDTaiLieu)
                            action = "TaiLieu";
                        else if (content.ContentParent == Constant.IDDownload)
                            action = "Download";
                        else if (listTemp.Contains(content.ContentParent))
                            action = "ChiTietTinTuc";

                        SearchResultItem searchItem = new SearchResultItem();
                        searchItem.Title = content.ContentTitle;
                        searchItem.PublishDate = content.PublishDate ?? DateTime.Now;
                        searchItem.Link = Url.Action(action, new { code = content.ContentCode });
                        searchResult.Add(searchItem);
                    }
                }
            }
            // -- search content

            int pageIndex = (page ?? 1) - 1;
            PaginatedList<SearchResultItem> model = new PaginatedList<SearchResultItem>(
                searchResult, pageIndex, Constant.PageSize);

            ViewData["CountResult"] = searchResult.Count;
            ViewData["Keyword"] = code;
            return View(model);
        }
        #endregion


        #region Gio Hang
        [HttpPost()]
        public JsonResult XoaSanPhamGioHang(int productID)
        {
            try
            {
                Dictionary<int, int> cart = Session["Cart"] as Dictionary<int, int>;
                cart.Remove(productID);
                Session["Cart"] = cart;
                int countCart = (int)Session["CountCart"];
                Session["CountCart"] = countCart - 1;

                return this.Json(new { mess = "Xóa thành công sản phẩm ra khỏi đơn hàng." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.Json(new { mess = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult CapNhatSoLuongSPGioHang(int productID, int count)
        {
            try
            {
                Dictionary<int, int> cart = Session["Cart"] as Dictionary<int, int>;
                if (cart.ContainsKey(productID))
                    cart[productID] = count;
                Session["Cart"] = cart;

                return this.Json(new { mess = "Cập nhật thành công số lượng sản phẩm." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.Json(new { mess = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult HoanTatGioHang(string code)
        {
            return View();
        }

        [HttpPost()]
        public ActionResult HoanTatGioHang(FormCollection collection)
        {
            string hoTen = collection["txtHoten"];
            string tenCty = collection["txtTenCty"];
            string dcCty = collection["txtDchiCty"];
            string dienThoai = collection["txtDienThoai"];
            string email = collection["txtEmail"];
            string code = collection["hidFileCode"];
            string fileTitle = string.Empty;
            string fileName = string.Empty;
            string fileExten = string.Empty;

            Dictionary<int, int> cart = Session["Cart"] as Dictionary<int, int>;
            List<int> listProductID = cart.Keys.ToList<int>();
            List<Product> listProduct = new List<Product>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ProductRepository productRepository = new ProductRepository(entity);
                listProduct = productRepository.GetListProductByListID(listProductID);
            }

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(email);
            mail.To.Add("nguyenthetrinh84@gmail.com");
            mail.Subject = "Thông tin giỏ hàng từ website tanhungviet.vn";
            mail.Body = "Đây là email tự động từ trang web tanhungviet.vn khi có khách hàng đăng ký mua hàng từ website"
                + "\n" + "\n"
                + "\t" + "Thông tin khách hàng đặt mua" + "\n"
                + "\t" + "\t" + "Họ tên : " + hoTen + "\n"
                + "\t" + "\t" + "Tên công ty : " + tenCty + "\n"
                + "\t" + "\t" + "Địa chỉ công ty : " + dcCty + "\n"
                + "\t" + "\t" + "Số điện thoại : " + dienThoai + "\n"
                + "\t" + "\t" + "Email : " + email + "\n" + "\n"
                + "\t" + "Thông tin giỏ hàng" + "\n";

            foreach (var item in listProduct)
            {
                string productName = item.ProductName;
                int count = cart[item.ProductID];
                mail.Body += "\t" + "\t" + count.ToString() + " - " + productName + "\n";
            }

            mail.IsBodyHtml = false;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            string userName, password;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ParameterRepository paramRepository = new ParameterRepository(entity);
                userName = paramRepository.GetParamValue(Constant.ParamEmailAcc);
                password = paramRepository.GetParamValue(Constant.ParamEmailPwd);
            }
            //TanHungViet.Helper.Util.GetMailInfo(out userName, out password);
            client.Credentials = new NetworkCredential(userName, password);
            client.EnableSsl = true;
            client.Send(mail);

            Session["Cart"] = new Dictionary<int, int>(); 
            return RedirectToAction("Index");
        }
        #endregion
    }
}
